﻿namespace System;

public static class HttpClientExtension
{
    public static async Task<string> PostAsync(this HttpClient http, string url, object param, Dictionary<string, string> header = null)
    {
        string json = string.Empty;
        if (param != null && param is string)
            json = param as string;
        else if (param != null && param != null)
            json = JsonSerializer.Serialize(param);

        using HttpContent content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        if (header?.Count > 0)
            foreach (KeyValuePair<string, string> kv in header)
                if (!content.Headers.Contains(kv.Key))
                    content.Headers.Add(kv.Key, kv.Value);

        using HttpResponseMessage response = await http.PostAsync(url, content);
        response.EnsureSuccessStatusCode();//用来抛异常的
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    public static async Task<T> PostAsync<T>(this HttpClient http, string url, object param, Dictionary<string, string> header = null) where T : class, new()
    {
        var json = await http.PostAsync(url, param, header);
        return json.ToObject<T>();
    }

}